package com.feifei.controller;

import com.feifei.bean.Product;
import com.feifei.bean.User;
import com.feifei.service.ProductService;
import com.feifei.service.UserService;
import com.feifei.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    ProductService productService;

    //注册功能
    @ResponseBody
    @RequestMapping("/user/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        int i = userService.addUser(user);
        if (i > 0) {
            map.put("msg", "添加用户成功");
            map.put("status", true);
        } else {
            map.put("msg", "注册失败");
            map.put("status", false);
        }
        System.out.println(user);
        return map;
    }

    //注册校验用户名是否重复
    @ResponseBody
    @RequestMapping("/user/checkUsername")
    public Map<String, Object> checkUsername(String username) {
        System.out.println(username);
        Map<String, Object> map = new HashMap<>();
        boolean flag = userService.checkUsername(username);
        System.out.println("flag = " + flag);
        if (flag) {
            map.put("msg", "该用户名已存在");
            map.put("status", false);
        } else {
            map.put("msg", "可以使用该用户名");
            map.put("status", true);
        }

        return map;
    }

    //实现登录功能
    @ResponseBody
    @RequestMapping("/user/login")
    public Map<String, Object> userLogin(@RequestBody User user, HttpSession session) {
        System.out.println("user = " + user);
        Map<String, Object> map = new HashMap<>();
        User user1 = userService.userLogin(user);
        System.out.println(user1);

        if (user1 != null) {
            session.setAttribute("userInfo", user1);
            map.put("msg", "登陆成功");
            map.put("status", true);
            map.put("userInfo", user1);
        } else {
            map.put("msg", "用户名或密码错误，请重新输入");
            map.put("status", false);
        }
        System.out.println(map.get("msg"));
        return map;
    }


}
